#ifndef JOLFS_TOOLS_FILESYSTEM_H
#define JOLFS_TOOLS_FILESYSTEM_H

#include <string>
#include <vector>
#include <algorithm>

#include <string.h>

namespace jolfs
{

//==============================================================================
// DECLARATIONS
//==============================================================================

// Constants
const std::string SEPARATOR = "/";

// Functions
static std::string              filename ( const std::string& path               );
static std::string              extension( const std::string& file               );
static std::vector<std::string> explode  ( const std::string& path               );
static std::string              implode  ( const std::vector<std::string>&  path );
static std::string              directory( const std::string& path               );

//==============================================================================
// DEFINITIONS
//==============================================================================

std::string filename( const std::string& path )
{
  std::size_t i = path.find_last_of( SEPARATOR );
  return path.substr( i+1 );
}

std::string extension( const std::string& file )
{
  std::string name = filename(file);
  std::size_t i = name.find_last_of( "." );
  if ( i==std::string::npos )
    return "";
  else
    return name.substr( i+1 );
}

std::vector<std::string> explode( const std::string& path )
{
  std::vector<std::string> result;
  char* str = new char[path.size()+1];
  strcpy( str, path.c_str() );
  char* pch = strtok( str, SEPARATOR.c_str() );
  while ( pch != 0 )
  {
    result.push_back( pch );
    pch = strtok( 0, SEPARATOR.c_str() );
  }
  return result;
}

std::string implode( const std::vector<std::string>& path )
{
  std::string result;
  
  std::vector<std::string>::const_iterator it = path.begin();
  for (; it!=path.end(); ++it )
    result += "/" + *it;
  
  return result;
}

// TODO: fix this for inputs without "/": "test", "file.ext", etc...
std::string directory( const std::string& path )
{
  std::size_t i = path.find_last_of( SEPARATOR );
  return path.substr( 0, i );
}

} // namespace jolfs

#endif // JOLFS_TOOLS_FILESYSTEM_H
